package process;

import data.Term;
import data.TermCollection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * TermRanker bertugas mengurutkan term dari dalam koleksi ke dalam sebuah 
 * priority queue
 * @author Muqtafi Akhmad
 */
public class TermRanker implements Runnable {

    /**
     * mengisikan antrian term
     * @param rankedTerm antrian term
     */
    public void setRankedTerm(PriorityQueue<Term> rankedTerm) {
        this.rankedTerm = rankedTerm;
    }

    /**
     * mengisikan term collection
     * @param termCollection term collection
     */
    public void setTermCollection(TermCollection termCollection) {
        this.termCollection = termCollection;
    }

    /**
     * mendapatkan priority  queue hasil ranking
     * @return priority queue
     */
    public PriorityQueue<Term> getRankedTerm() {
        return rankedTerm;
    }

    /**
     * mendapatkan term collection yang direfernsi
     * @return term collection
     */
    public TermCollection getTermCollection() {
        return termCollection;
    }
    /**
     * term collection
     */
    private TermCollection termCollection;
    /**
     * term yang telah diranking
     */
    private PriorityQueue<Term> rankedTerm;

    /**
     * Konstruktor dari TermRanker
     * @param rankedTermContainer antrian term penampung hasil ranking
     * @param termCollection koleksi term
     */
    public TermRanker(PriorityQueue<Term> rankedTermContainer, TermCollection termCollection) {
        this.rankedTerm = rankedTermContainer;
        this.termCollection = termCollection;
    }

    /**
     * mendapatkan top terms dari antrian
     * @param termCount jumlah top term
     * @return koleksi top term
     */
    public ArrayList<Term> getTopTerms(Integer termCount) {
        int i;
        if (this.rankedTerm.size() < termCount) {
            termCount = this.rankedTerm.size();
        }
        ArrayList<Term> result = new ArrayList<Term>();
        for (i = 0; i < termCount; i++) {
            result.add(this.rankedTerm.poll());
        }
        return result;
    }

    /**
     * menjalankan proses ranking, menambahkan term dalam term collection 
     * ke dalam antrian priority queue
     */
    @Override
    public void run() {
        HashMap<String, Term> termsExtracted = termCollection.getAllTerms();
        Iterator it = termsExtracted.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            Term term = (Term) pairs.getValue();
            rankedTerm.add(term);
        }
    }
}
